import requests
from config.config import Config
import mimetypes
from io import BytesIO
import os
# import yaml

# class Config:
#     # 数据库配置
#     SQLALCHEMY_DATABASE_URI = os.getenv(
#         "DATABASE_URL", "postgresql://user:password@localhost/mindcare"
#     )
#     SQLALCHEMY_TRACK_MODIFICATIONS = False

#     # JWT配置
#     JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "your_jwt_secret_key")
#     JWT_ACCESS_TOKEN_EXPIRES = 900  # 15分钟
#     JWT_REFRESH_TOKEN_EXPIRES = 604800  # 7天

#     # Redis配置
#     REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")

#     # 短信服务配置（以阿里云为例）
#     SMS_ACCESS_KEY_ID = os.getenv("SMS_ACCESS_KEY_ID")
#     SMS_ACCESS_KEY_SECRET = os.getenv("SMS_ACCESS_KEY_SECRET")
#     SMS_SIGN_NAME = "MindCare"
#     SMS_TEMPLATE_CODE = "SMS_123456789"

#     """
#     简单的配置类，将YAML文件内容直接映射为类属性。
#     只处理第一层级，更深的层级将以字典形式存储。
#     """

#     config_path = None

#     @classmethod
#     def load_config(cls, file_path):
#         # if cls.config_path is not None:
#             # return
#         cls.config_path = file_path
#         with open(file_path, 'r', encoding='utf-8') as f:
#             config_dict = yaml.safe_load(f)

#         # 设置类属性
#         for key, value in config_dict.items():
#             setattr(cls, key, value)


# Config.load_config('./config/config.yaml')

class AudioTranscriber:
    def __init__(self, api_key=None, model="FunAudioLLM/SenseVoiceSmall"):
        """
        初始化 AudioTranscriber 实例。
        
        :param api_key: 你的API密钥
        :param model: 使用的模型名称，默认是 "FunAudioLLM/SenseVoiceSmall"
        """
        self.api_key = api_key if api_key is not None else Config.stt["OPENAI_API_KEY"]
        self.model = Config.stt["model"]
        self.url = Config.stt["BASE_URL"]
    
    def transcribe(self, audio_data: BytesIO, filename: str = "audio", content_type: str = None):
        """
        将音频字节流转写为文本
        
        :param audio_data: 音频字节流（BytesIO 对象）
        :param filename: 原始文件名（用于推断内容类型）
        :param content_type: 可选，显式指定内容类型，如 "audio/mp3"
        :return: 转写结果字符串 或 错误信息
        """
        headers = {
            "Authorization": f"Bearer {self.api_key}"
        }

        # 自动检测 MIME 类型
        if content_type is None:
            guessed_type, _ = mimetypes.guess_type(filename)
            if guessed_type and guessed_type.startswith("audio/"):
                content_type = guessed_type
            else:
                content_type = "audio/x-unknown"

        # 准备上传数据
        files = {
            "file": (filename, audio_data, content_type)
        }
        data = {
            "model": self.model
        }

        # 发送请求
        response = requests.post(self.url, headers=headers, files=files, data=data)

        if response.status_code == 200:
            return response.json().get("text", "")
        else:
            return f"请求失败，状态码: {response.status_code}, 错误信息: {response.text}"


# 使用示例
if __name__ == "__main__":
    # 替换为你的API密钥和音频文件路径
    audio_file_path = "./data/emo_3.wav"  # 替换为你的音频文件路径
    transcriber = AudioTranscriber()
    if not os.path.exists(audio_file_path):
        print(f"文件 {audio_file_path} 不存在")
    
    # 使用 BytesIO 读取文件
    with open(audio_file_path, "rb") as f:
        # audio_data = BytesIO(f.read())
    
    # 调用 transcribe 方法
        result = transcriber.transcribe(audio_data=f, content_type="audio/wav")
    
    # 打印结果
    print("转写结果:", result)